package com.omri.when.there;

import java.sql.SQLDataException;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Db {

	public static final String KEY_ROWID = "_id";
	public static final String KEY_TITLE = "Title_name";
	public static final String KEY_DESCRIPTION = "Description";
	public static final String KEY_LAT = "Lat";
	public static final String KEY_LNG = "Lng";

	private static final String DATABASE_NAME = "whenThereDB";
	private static final String DATABASE_TABLE = "reminderTable";
	private static final int DATABASE_VERSION = 1;

	private DBHealper ourHealper;
	private final Context ourContext;
	private SQLiteDatabase ourDatabase;

	private static class DBHealper extends SQLiteOpenHelper {

		public DBHealper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + 
			KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 
			KEY_TITLE + " TEXT NOT NULL, " + 
			KEY_DESCRIPTION + " TEXT NOT NULL, " +
		    KEY_LAT + " FLOAT, " + 
			KEY_LNG + " FLOAT);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
	}

	public Db(Context c) {
		ourContext = c;
	}
	public Db write()throws SQLDataException{
		ourHealper = new DBHealper(ourContext);
		ourDatabase = ourHealper.getWritableDatabase();
		return this;
	}
	public void close(){
		ourHealper.close();
	}
	public long createEntry(String title, String description, Float latitude, Float longitude) {
		// TODO Auto-generated method stub
		ContentValues cv = new ContentValues();
		cv.put(KEY_TITLE, title);
		cv.put(KEY_DESCRIPTION, description);
		cv.put(KEY_LAT, latitude);
		cv.put(KEY_LNG, longitude);
		return ourDatabase.insert(DATABASE_TABLE, null, cv);
	}
}